<style scoped>
.add-outside-image .image {
  display: flex;
  justify-content: center;
  align-items: center;
}
.add-outside-image .el-form-item {
  margin-bottom: 0;
}
</style>
<!-- 添加外链接图片地址弹窗编辑器 -->
<template>
  <div class="add-outside-image">
    <el-dialog @close="close" title="添加外链图片" :close-on-click-modal="false" :visible.sync="centerDialogVisible" :modal-append-to-body="false" width="40%" center>
      <el-form ref="form" label-width="80px" @submit.native.prevent>
        <el-form-item label="外链地址">
          <el-input @change="changeLink" size="medium" v-model="link"></el-input>
          <el-alert v-if="error" style="height: 30px;" :title="error" type="error">
          </el-alert>
        </el-form-item>
      </el-form>
      <div class="image" v-if="link && !error">
        <el-image @load="imageLoad" @error="imageError" :src="link">
          <div slot="error" class="image-slot">
            <i style="font-size: 100px;color:#a5a5a5;" class="el-icon-picture-outline"></i>
            <p style="text-align: center;">图片链接失效</p>
          </div>
        </el-image>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="centerDialogVisible = false">取 消</el-button>
        <el-button :disabled="!isok" size="small" type="primary" @click="ok">添 加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    getLink: {
      type: Function
    }
  },
  data () {
    return {
      centerDialogVisible: false,
      link: '',
      error: '',
      isok: false
    }
  },
  methods: {
    imageLoad () {
      this.error = ''
      this.isok = true
    },
    imageError () {
      this.error = '输入的图片链接地址无效'
      this.isok = false
    },
    close () {
      this.centerDialogVisible = false
      this.link = ''
      this.error = ''
    },
    open () {
      this.centerDialogVisible = true
    },
    changeLink () {
      if (this.link === '') {
        this.error = '外链地址不能为空'
        return
      }

      let reg = /^(http:\/\/|https:\/\/|\/\/)[\w\-_]+(\.[\w\-_]+)+\/(.*?)/
      if (!reg.test(this.link)) {
        this.error = '输入的图片链接地址无效'
        return
      }

      this.error = ''
    },
    ok () {
      this.getLink(this.link)
      this.centerDialogVisible = false
    }
  }
}

</script>
